let type = 'pro'
let BASE_URL = 'http://192.168.8.109:9526'

const API_URL = {
	dev: 'http://192.168.8.109:9526',
	uat: 'https://cf-patrol.jsdhqy.cn',
	mock: 'http://2.34.30.2:9995',
	pro: 'https://cf-patrol.jsdhqy.cn'
}

BASE_URL = API_URL[type]
const UPLOAD_URL = BASE_URL + '/index.php/mini/suishoupai.Suishoupai/upload'

import Router from '../common/router/index'

// 普通请求
export function request(options) {
	return new Promise((resolve, reject) => {
		const {
			isToken,
			isJson
		} = options

    let _header = {}
    let _url = ''

		if (isJson) {
			_header = {
				'Content-Type': 'application/json'
			}
		} else {
			//   x-www-form-unlencoded
			_header = {
				'Content-Type': 'application/x-www-form-unlencoded'
			}
		}

		if (isToken) {
			_header.accessToken = uni.getStorageSync('_accessToken') || ''
    }

    if (type === 'dev')
    {
      _url = BASE_URL + options.url
    } else
    {
      _url = BASE_URL + '/index.php' + options.url
    }
		uni.request({
			header: _header,
			// url: BASE_URL + '/index.php' + options.url,
      url: _url,
			method: options.method || 'GET',
			data: options.data || {},
			success: (res) => {
				const {
					data
				} = res;
				// console.log("request----------",JSON.stringify(res));
				// 正常返回
				if (data.code === 200) {
					resolve(data.result)
        }
        // 一般错误
				else if (data.code === 400) {
						uni.showToast({
							title: data.message || '一般错误',
							icon: 'none',
							mask: true
						})
						reject(false)
				}
				// 服务器错误
				else if (data.code === 500) {
						uni.showToast({
							title: data.message || '系统错误',
							icon: 'none',
							mask: true
						})
						reject(false)
					// }
				}

				// 登录错误
        else if (data.code === 401)
        {
          uni.showToast({
            title: data.message,
            icon: 'none',
            mask: true
          })
          setTimeout(() => {
            // reject(data)
            uni.removeStorageSync('_accessToken')
            // uni.removeStorageSync('_userInfo')
            uni.removeStorageSync('_phone')
						Router.push({
							name: 'home'
						})
					}, 1000)
				}

				// 系统错误
				else {
					// console.log('未知错误-----', JSON.stringify(data))
					uni.showToast({
						title: '未知错误',
						icon: 'none',
						mask: true
					})
					reject(false)
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '请求失败',
					icon: 'none',
					mask: true
				})
				reject(err)
			}
		})
	})
}
export {
	BASE_URL,
	UPLOAD_URL
}